package com.cheyunkeji.er.fragment.evaluate;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.CarSourceCitySelectActivity;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.activity.evaluate.PhotoPreViewActivity;
import com.cheyunkeji.er.activity.evaluate.SelectCarInfoActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.CarBaseInfoData;
import com.cheyunkeji.er.bean.evaluate.CarInfo;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.bean.evaluate.VehicleInfoBean;
import com.cheyunkeji.er.bean.event.RefreshUIEvent;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.utils.ImageLoadUtil;
import com.cheyunkeji.er.utils.TimeUtils;
import com.cheyunkeji.er.view.DatePickerUtil;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.evaluate.ImageSelectDialog;
import com.cheyunkeji.er.view.evaluate.TakePhotoDisplayView;
import com.cheyunkeji.er.view.evaluate.wheel_selector.IListPickerOK;
import com.cheyunkeji.er.view.evaluate.wheel_selector.InfoData;
import com.cheyunkeji.er.view.evaluate.wheel_selector.ListPicker;
import com.cheyunkeji.er.view.evaluate.wheel_selector.PickData;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.qqtheme.framework.picker.DatePicker;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;
import okhttp3.Call;
import okhttp3.Request;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Michael on 2017/3/28 13:40.
 */

public class CarBaseInfoFragment extends BaseFragment implements IListPickerOK, EvaluateWorkflowActivity.OnOutActionListener, TakePhotoDisplayView.OnTakePhotoListener, OssService.onImageProcessedResultListener, ImageSelectDialog.ImageSelectListener, DatePicker.OnYearMonthDayPickListener ,SDialog.SDialogListener {

    public static final int PAGE_INDEX = 1;
    private static final int PARAMS_NOT_NECESSARY = -1;
    private static final int PARAMS_LEVEL_CAR_VEHICLE_MANUFACTORY = 4;
    private static final String TAG = CarBaseInfoFragment.class.getSimpleName();
    private static final int PREVIEW_IMG_REQUEST = 0x110;
    private static final int REQUEST_CODE_SELECT_SOURCE_CITY = 0x120;
    private static final int REQUEST_CODE_SELECT_CAR_BRAND = 0x121;
    private static final int REQUEST_CODE_SELECT_CAR_SERIES = 0x122;
    private static final int REQUEST_CODE_SELECT_CAR_MODEL = 0x123;

    @BindView(R.id.tv_previous_step)
    TextView tvPreviousStep;
    @BindView(R.id.tv_next_step)
    TextView tvNextStep;
    @BindView(R.id.ll_bottom_view)
    LinearLayout llBottomView;
    @BindView(R.id.et_dashboard_mileage)
    EditText etDashboardMileage;
    @BindView(R.id.iv_star1)
    ImageView ivStar1;
    @BindView(R.id.tv_car_source_city)
    TextView tvCarSourceCity;
    @BindView(R.id.ll_car_source_city)
    LinearLayout llCarSourceCity;
    @BindView(R.id.tv_shangpai_date)
    TextView tvShangpaiDate;
    @BindView(R.id.iv_register_date)
    ImageView ivRegisterDate;
    @BindView(R.id.tv_carbody_color)
    TextView tvCarbodyColor;
    @BindView(R.id.ll_carbody_color)
    LinearLayout llCarbodyColor;
    @BindView(R.id.et_guohu_count)
    EditText etGuohuCount;
    @BindView(R.id.tv_use_type)
    TextView tvUseType;
    @BindView(R.id.ll_use_type)
    LinearLayout llUseType;
    @BindView(R.id.tv_insurance_date)
    TextView tvInsuranceDate;
    @BindView(R.id.iv_insurance_date)
    ImageView ivInsuranceDate;
    @BindView(R.id.tv_annual_inspect_date)
    TextView tvAnnualInspectDate;
    @BindView(R.id.iv_annual_inspect)
    ImageView ivAnnualInspect;
    @BindView(R.id.tv_car_brand)
    TextView tvCarBrand;
    @BindView(R.id.ll_car_brand)
    LinearLayout llCarBrand;
    @BindView(R.id.tv_car_series)
    TextView tvCarSeries;
    @BindView(R.id.ll_car_series)
    LinearLayout llCarSeries;
    @BindView(R.id.tv_car_model)
    TextView tvCarModel;
    @BindView(R.id.ll_car_model)
    LinearLayout llCarModel;
    @BindView(R.id.tv_car_age)
    TextView tvCarAge;
    @BindView(R.id.ll_car_age)
    LinearLayout llCarAge;
    @BindView(R.id.tv_chuchang_date)
    TextView tvChuchangDate;
    @BindView(R.id.iv_chuchang)
    ImageView ivChuchang;
    @BindView(R.id.tv_car_body_style)
    TextView tvCarBodyStyle;
    @BindView(R.id.ll_car_body_style)
    LinearLayout llCarBodyStyle;
    @BindView(R.id.tv_bsx)
    TextView tvBsx;
    @BindView(R.id.ll_bsx)
    LinearLayout llBsx;
    @BindView(R.id.tv_pfbz)
    TextView tvPfbz;
    @BindView(R.id.ll_pfbz)
    LinearLayout llPfbz;
    @BindView(R.id.et_pl)
    EditText etPl;
    @BindView(R.id.tv_pl_unit)
    TextView tvPlUnit;
    @BindView(R.id.ll_pl_unit)
    LinearLayout llPlUnit;
    @BindView(R.id.tv_gas_type)
    TextView tvGasType;
    @BindView(R.id.ll_gas_type)
    LinearLayout llGasType;
    @BindView(R.id.tv_drive_type)
    TextView tvDriveType;
    @BindView(R.id.ll_drive_type)
    LinearLayout llDriveType;
    @BindView(R.id.tv_car_gs)
    TextView tvCarGs;
    @BindView(R.id.ll_car_gs)
    LinearLayout llCarGs;
    @BindView(R.id.tv_seat_count)
    TextView tvSeatCount;
    @BindView(R.id.ll_seat_count)
    LinearLayout llSeatCount;
    //    @BindView(R.id.et_engine_power)
//    EditText etEnginePower;
    @BindView(R.id.et_palate_number)
    EditText etPalateNumber;
    @BindView(R.id.et_engine_number)
    EditText etEngineNumber;
    @BindView(R.id.tv_jsc_color)
    TextView tvJscColor;
    @BindView(R.id.ll_jsc_color)
    LinearLayout llJscColor;
    @BindView(R.id.tv_insurance_company)
    TextView tvInsuranceCompany;
    @BindView(R.id.ll_insurance_company)
    LinearLayout llInsuranceCompany;
    @BindView(R.id.rb_gzszs_checked)
    RadioButton rbGzszsChecked;
    @BindView(R.id.rb_gzszs_unchecked)
    RadioButton rbGzszsUnchecked;
    @BindView(R.id.rg_gzs_zs)
    RadioGroup rgGzsZs;
    @BindView(R.id.rb_voucher_checked)
    RadioButton rbVoucherChecked;
    @BindView(R.id.rb_voucher_unchecked)
    RadioButton rbVoucherUnchecked;
    @BindView(R.id.rg_newcar_voucher)
    RadioGroup rgNewcarVoucher;
    @BindView(R.id.rb_license_checked)
    RadioButton rbLicenseChecked;
    @BindView(R.id.rb_license_unchecked)
    RadioButton rbLicenseUnchecked;
    @BindView(R.id.rg_car_license)
    RadioGroup rgCarLicense;
    @BindView(R.id.rb_certificate_checked)
    RadioButton rbCertificateChecked;
    @BindView(R.id.rb_certificate_unchecked)
    RadioButton rbCertificateUnchecked;
    @BindView(R.id.rg_car_certification)
    RadioGroup rgCarCertification;
    @BindView(R.id.rb_qzbxd_checked)
    RadioButton rbQzbxdChecked;
    @BindView(R.id.rb_qzbxd_unchecked)
    RadioButton rbQzbxdUnchecked;
    @BindView(R.id.rg_qz_bxd)
    RadioGroup rgQzBxd;
    @BindView(R.id.rb_bykey_checked)
    RadioButton rbBykeyChecked;
    @BindView(R.id.rb_bykey_unchecked)
    RadioButton rbBykeyUnchecked;
    @BindView(R.id.rg_second_key)
    RadioGroup rgSecondKey;
    @BindView(R.id.rb_wclwfjl_checked)
    RadioButton rbWclwfjlChecked;
    @BindView(R.id.rb_wclwfjl_unchecked)
    RadioButton rbWclwfjlUnchecked;
    @BindView(R.id.rg_wcl_wfjl)
    RadioGroup rgWclWfjl;
    @BindView(R.id.rb_sfcf_checked)
    RadioButton rbSfcfChecked;
    @BindView(R.id.rb_sfcf_unchecked)
    RadioButton rbSfcfUnchecked;
    @BindView(R.id.rg_sf_cfdy)
    RadioGroup rgSfCfdy;
    @BindView(R.id.rb_dp_checked)
    RadioButton rbDpChecked;
    @BindView(R.id.rb_dp_unchecked)
    RadioButton rbDpUnchecked;
    @BindView(R.id.rg_dp)
    RadioGroup rgDp;
    @BindView(R.id.rb_cartax_checked)
    RadioButton rbCartaxChecked;
    @BindView(R.id.rb_cartax_unchecked)
    RadioButton rbCartaxUnchecked;
    @BindView(R.id.rg_cartax_receipt)
    RadioGroup rgCartaxReceipt;
    @BindView(R.id.rb_sybx_checked)
    RadioButton rbSybxChecked;
    @BindView(R.id.rb_sybx_unchecked)
    RadioButton rbSybxUnchecked;
    @BindView(R.id.rg_commercial_insurance)
    RadioGroup rgCommercialInsurance;
    @BindView(R.id.tpdv_01)
    TakePhotoDisplayView tpdv01;
    @BindView(R.id.tpdv_02)
    TakePhotoDisplayView tpdv02;
    @BindView(R.id.tpdv_03)
    TakePhotoDisplayView tpdv03;
    @BindView(R.id.tpdv_04)
    TakePhotoDisplayView tpdv04;
    @BindView(R.id.tpdv_05)
    TakePhotoDisplayView tpdv05;
    @BindView(R.id.tpdv_06)
    TakePhotoDisplayView tpdv06;
    @BindView(R.id.tpdv_07)
    TakePhotoDisplayView tpdv07;
    @BindView(R.id.tpdv_08)
    TakePhotoDisplayView tpdv08;
    @BindView(R.id.iv_goto_top)
    ImageView ivGotoTop;
    @BindView(R.id.ll_photo_selecter)
    LinearLayout llPhotoSelecter;
    @BindView(R.id.sv_content)
    ScrollView svContent;
    @BindView(R.id.ll_root_view)
    RelativeLayout llRootView;
    @BindView(R.id.tv_chemen_count)
    TextView tvChemenCount;
    @BindView(R.id.ll_chemen_count)
    LinearLayout llChemenCount;
    @BindView(R.id.tv_sccj)
    TextView tvSccj;
    @BindView(R.id.ll_sccj)
    LinearLayout llSccj;

    private ImageSelectDialog imgSelectDialog;

    private ImageCaptureManager captureManager;

    //    当前选中车辆品牌
    private CarInfo.CarBrand selectedCarBrand;
    //    当前选中车型
    private CarInfo.CarModel selectedCarModel;
    //    当前选中车系
    private CarInfo.CarSeries selectedCarSeries;
    //         当前选中生产厂家
    private CarInfo.CarManufactory selectedManufactory;

    private HashMap<String, String> params = new HashMap<>();

    private Calendar calendar;
    private ListPicker listPicker;
    private ArrayList dataList;

    private EvaluateDetailResult2 evaluateResult;

    private ArrayList<TakePhotoDisplayView> photoViewList = null;
    private int uploadImgCounter = 0;
    private HashMap<String, String> imgParams = null;
    private Runnable mTask;
    private SDialog dialog ;

    @Override
    protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
        contentView = inflater.inflate(R.layout.er_frag_car_base_info, container, false);
        ButterKnife.bind(this, contentView);
        EventBus.getDefault().register(CarBaseInfoFragment.this);
    }

    @Override
    protected void init() {
        calendar = Calendar.getInstance();
        captureManager = new ImageCaptureManager(this.getActivity());
        listPicker = new ListPicker(getActivity(), this, llRootView);
        dataList = new ArrayList<>();
        if (params == null) {
            params = new HashMap<>();
        }
        if (null != MyApplication.getInstance().getEvaluateResult()) {
            evaluateResult = MyApplication.getInstance().getEvaluateResult();
            displayInfo();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshUIEvent event) {
        if (null != MyApplication.getInstance().getEvaluateResult()) {
            evaluateResult = MyApplication.getInstance().getEvaluateResult();
            displayInfo();
            Log.e(TAG, "onMessageEvent: msg received ");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(VehicleInfoBean data) {
        if (null != data) {
            Log.e(TAG, "onMessageEvent: " + data.getCustomer());
            displayDataInfo(data);
        }
    }

    /**
     * 回填vin查询结果
     */
    private void displayDataInfo(VehicleInfoBean data) {
        if (!TextUtils.isEmpty(data.getMileage()) && !TextUtils.equals(data.getMileage(), "0")) {
            etDashboardMileage.setText(data.getMileage());
        }

        if (!TextUtils.isEmpty(data.getLicdate())) {
            tvShangpaiDate.setText(TimeUtils.millis10bitToStringWithoutHMS(data.getLicdate()));
        }

        if (!TextUtils.isEmpty(data.getExwdate()) && !data.getExwdate().equals("0"))
            tvChuchangDate.setText(TimeUtils.millis10bitToStringWithoutHMS(data.getExwdate()));

        tvCarbodyColor.setText(data.getExteriorcolor_name());
        params.put("exteriorcolor", data.getExteriorcolor());

        tvCarbodyColor.setText(data.getExteriorcolor_name());
        params.put("exteriorcolor", data.getExteriorcolor());

        if (!TextUtils.isEmpty(data.getTransfers()) && 0 != Integer.valueOf(data.getTransfers()))
            etGuohuCount.setText(data.getTransfers());

        tvUseType.setText(MyApplication.getInstance().getCarTempAttrList().getAr_isuse().get(Integer.valueOf(data.getIsuse())));
        params.put("isuse", data.getIsuse());

        if (!TextUtils.isEmpty(data.getTcidate()) && !data.getTcidate().equals("0"))
            tvInsuranceDate.setText(TimeUtils.millis10bitToStringWithoutHMS(data.getTcidate()));

        if (!TextUtils.isEmpty(data.getVaidate()) && !data.getVaidate().equals("0"))
            tvAnnualInspectDate.setText(TimeUtils.millis10bitToStringWithoutHMS(data.getVaidate()));

        if (!TextUtils.isEmpty(data.getBrand_name())) {
            tvCarBrand.setText(data.getBrand_name());

            if (null == selectedCarBrand)
                selectedCarBrand = new CarInfo.CarBrand(data.getBrand(), data.getBrand_name(), "");
            else {
                selectedCarBrand.setId(data.getBrand());
                selectedCarBrand.setTitle(data.getBrand_name());
            }
        }

        if (!TextUtils.isEmpty(data.getSeries_name()))
            tvCarSeries.setText(data.getSeries_name());
        if (null == selectedCarSeries)
            selectedCarSeries = new CarInfo.CarSeries(data.getSeries(), data.getSeries_name());
        else {
            selectedCarSeries.setId(data.getSeries());
            selectedCarSeries.setTitle(data.getSeries_name());
        }

        if (!TextUtils.isEmpty(data.getSpec_name())) {
            tvCarModel.setText(data.getSpec_name());
            if (null == selectedCarModel)
                selectedCarModel = new CarInfo.CarModel(data.getSpec(), data.getSpec_name());
            else {
                selectedCarModel.setId(data.getSpec());
                selectedCarModel.setTitle(data.getSpec_name());
            }
        }

        if (!TextUtils.isEmpty(data.getFacturer()) && !TextUtils.isEmpty(data.getFacturer_name())) {
            tvSccj.setText(data.getFacturer_name());
            if (null == selectedManufactory) {
                selectedManufactory = new CarInfo.CarManufactory(data.getFacturer(), data.getFacturer_name());
            } else {
                selectedManufactory.setId(data.getFacturer());
                selectedManufactory.setTitle(data.getFacturer_name());
            }
        }

        tvCarAge.setText(data.getCyear_name());
        params.put("cyear", data.getCyear());

        tvCarBodyStyle.setText(data.getBodystyle_name());
        params.put("bodystyle", data.getBodystyle());

        Log.e(TAG, "displayDataInfo 变速箱: " + data.getTrans_name() );
        Log.e(TAG, "displayDataInfo: 变速箱 id " + data.getTrans()  );

        tvBsx.setText(data.getTrans_name());
        params.put("trans", data.getTrans());

        tvPfbz.setText(data.getEmission_name());
        params.put("emission", data.getEmission());

        if (!TextUtils.isEmpty(data.getDisplace()) && !data.getDisplace().equals("0")) {
            etPl.setText(data.getDisplace());
        }

        if (!TextUtils.isEmpty(data.getDispunit()) && !data.getDispunit().equals("0")) {
            tvPlUnit.setText(data.getDispunit());
        }

        tvGasType.setText(data.getFueltype_name());
        params.put("fueltype", data.getFueltype());

        tvDriveType.setText(data.getDrivetrain_name());
        params.put("drivetrain", data.getDrivetrain());

        tvCarGs.setText(data.getCylinders_name());
        params.put("cylinders", data.getCylinders());

        tvSeatCount.setText(data.getSeats_name());
        params.put("seats", data.getSeats());

        tvChemenCount.setText(data.getDoor_name());
        params.put("door", data.getDoor());

        if (!TextUtils.isEmpty(data.getPlate())) {
            etPalateNumber.setText(data.getPlate());
        }

        if (!TextUtils.isEmpty(data.getEngineno())) {
            etEngineNumber.setText(data.getEngineno());
        }

        tvJscColor.setText(data.getInteriorcolor_name());
        params.put("interiorcolor", data.getInteriorcolor());
    }

    //   展示界面数据
    private void displayInfo() {
        if (!TextUtils.isEmpty(evaluateResult.getMileage()) && !evaluateResult.getMileage().equals("0"))
            etDashboardMileage.setText(evaluateResult.getMileage());

        tvCarSourceCity.setText(evaluateResult.getProvince_name() + evaluateResult.getCity_name());
        params.put("city", evaluateResult.getCity());

        if (!TextUtils.isEmpty(evaluateResult.getExwdate()) && !evaluateResult.getExwdate().equals("0"))
            tvChuchangDate.setText(TimeUtils.millis10bitToStringWithoutHMS(evaluateResult.getExwdate()));

        if (!TextUtils.isEmpty(evaluateResult.getLicdate()) && !evaluateResult.getLicdate().equals("0"))
            tvShangpaiDate.setText(TimeUtils.millis10bitToStringWithoutHMS(evaluateResult.getLicdate()));


        tvCarbodyColor.setText(evaluateResult.getExteriorcolor_name());
        params.put("exteriorcolor", evaluateResult.getExteriorcolor());

        if (!TextUtils.isEmpty(evaluateResult.getTransfers()) && 0 != Integer.valueOf(evaluateResult.getTransfers()))
            etGuohuCount.setText(evaluateResult.getTransfers());

        if (!TextUtils.isEmpty(evaluateResult.getIsuse()))
            tvUseType.setText(MyApplication.getInstance().getCarTempAttrList().getAr_isuse().get(Integer.valueOf(evaluateResult.getIsuse())));

        if (!TextUtils.isEmpty(evaluateResult.getTcidate()) && !evaluateResult.getTcidate().equals("0"))
            tvInsuranceDate.setText(TimeUtils.millis10bitToStringWithoutHMS(evaluateResult.getTcidate()));

        if (!TextUtils.isEmpty(evaluateResult.getVaidate()) && !evaluateResult.getVaidate().equals("0"))
            tvAnnualInspectDate.setText(TimeUtils.millis10bitToStringWithoutHMS(evaluateResult.getVaidate()));

        if (!TextUtils.isEmpty(evaluateResult.getBrand_name())) {
            tvCarBrand.setText(evaluateResult.getBrand_name());
            selectedCarBrand = new CarInfo.CarBrand(evaluateResult.getBrand(), evaluateResult.getBrand_name(), "");
        }
        if (!TextUtils.isEmpty(evaluateResult.getSeries_name())) {
            tvCarSeries.setText(evaluateResult.getSeries_name());
            selectedCarSeries = new CarInfo.CarSeries(evaluateResult.getSeries(), evaluateResult.getSeries_name());
        }

        if (!TextUtils.isEmpty(evaluateResult.getSpec_name())) {
            tvCarModel.setText(evaluateResult.getSpec_name());
            selectedCarModel = new CarInfo.CarModel(evaluateResult.getSpec(), evaluateResult.getSpec_name());
        }

        if (!TextUtils.isEmpty(evaluateResult.getFacturer_name())) {
            tvSccj.setText(evaluateResult.getFacturer_name());
            selectedManufactory = new CarInfo.CarManufactory(evaluateResult.getFacturer(), evaluateResult.getFacturer_name());
        }

        tvCarAge.setText(evaluateResult.getCyear_name());
        params.put("cyear", evaluateResult.getCyear());

        tvCarBodyStyle.setText(evaluateResult.getBodystyle_name());
        params.put("bodystyle", evaluateResult.getBodystyle());

        tvBsx.setText(evaluateResult.getTrans_name());
        params.put("trans", evaluateResult.getTrans());

        tvPfbz.setText(evaluateResult.getEmission_name());
        params.put("emission", evaluateResult.getEmission());

        if (!TextUtils.isEmpty(evaluateResult.getDisplace()) && !evaluateResult.getDisplace().equals("0")) {
            etPl.setText(evaluateResult.getDisplace());
        }

        if (!TextUtils.isEmpty(evaluateResult.getDispunit()) && !evaluateResult.getDispunit().equals("0")) {
            tvPlUnit.setText(evaluateResult.getDispunit());
        }

        tvGasType.setText(evaluateResult.getFueltype_name());
        params.put("fueltype", evaluateResult.getFueltype());

        tvDriveType.setText(evaluateResult.getDrivetrain_name());
        params.put("drivetrain", evaluateResult.getDrivetrain());

        tvCarGs.setText(evaluateResult.getCylinders_name());
        params.put("cylinders", evaluateResult.getCylinders());

        tvSeatCount.setText(evaluateResult.getSeats_name());
        params.put("seats", evaluateResult.getSeats());

        tvChemenCount.setText(evaluateResult.getDoor_name());
        params.put("door", evaluateResult.getDoor());

        if (!TextUtils.isEmpty(evaluateResult.getPlate())) {
            etPalateNumber.setText(evaluateResult.getPlate());
        }

        if (!TextUtils.isEmpty(evaluateResult.getEngineno())) {
            etEngineNumber.setText(evaluateResult.getEngineno());
        }

        tvJscColor.setText(evaluateResult.getInteriorcolor_name());
        params.put("interiorcolor", evaluateResult.getInteriorcolor());


        tvInsuranceCompany.setText(evaluateResult.getInsurer_name());
        params.put("insurer", evaluateResult.getInsurer());

        rgGzsZs.check(evaluateResult.getVpt().equals("1") ? R.id.rb_gzszs_checked : R.id.rb_gzszs_unchecked);
        rgNewcarVoucher.check(evaluateResult.getInvoice().equals("1") ? R.id.rb_voucher_checked : R.id.rb_voucher_unchecked);
        rgCarLicense.check(evaluateResult.getVelic().equals("1") ? R.id.rb_license_checked : R.id.rb_license_unchecked);
        rgCarCertification.check(evaluateResult.getVrlic().equals("1") ? R.id.rb_certificate_checked : R.id.rb_certificate_unchecked);
        rgQzBxd.check(evaluateResult.getTcilic().equals("1") ? R.id.rb_qzbxd_checked : R.id.rb_qzbxd_unchecked);
        rgSecondKey.check(evaluateResult.getSparekey().equals("1") ? R.id.rb_bykey_checked : R.id.rb_bykey_unchecked);
        rgWclWfjl.check(evaluateResult.getNorecord().equals("1") ? R.id.rb_wclwfjl_checked : R.id.rb_wclwfjl_unchecked);
        rgSfCfdy.check(evaluateResult.getMortgage().equals("1") ? R.id.rb_sfcf_checked : R.id.rb_sfcf_unchecked);
        rgDp.check(evaluateResult.getCarryplate().equals("1") ? R.id.rb_dp_checked : R.id.rb_dp_unchecked);
        rgCartaxReceipt.check(evaluateResult.getCcsp().equals("1") ? R.id.rb_cartax_checked : R.id.rb_cartax_unchecked);
        rgCommercialInsurance.check(evaluateResult.getVci().equals("1") ? R.id.rb_sybx_checked : R.id.rb_sybx_unchecked);

//        load image
        if (null != evaluateResult.getImage()) {
            if (!TextUtils.isEmpty(evaluateResult.getImage().getWgzp1())) {
                ImageLoadUtil.loadImgInFrag(this, evaluateResult.getImage().getWgzp1(), tpdv01.getImageView());
                tpdv01.setImgPath(evaluateResult.getImage().getWgzp1());
                tpdv01.setPhotoBtnState(true);
            }

            if (!TextUtils.isEmpty(evaluateResult.getImage().getWgzp2())) {
                Log.e(TAG, "displayInfo: 外观照片2 ：  " + evaluateResult.getImage().getWgzp2());
                ImageLoadUtil.loadImgInFrag(this, evaluateResult.getImage().getWgzp2(), tpdv02.getImageView());
                tpdv02.setImgPath(evaluateResult.getImage().getWgzp2());
                tpdv02.setPhotoBtnState(true);
            }

            if (!TextUtils.isEmpty(evaluateResult.getImage().getWgzp3())) {
                ImageLoadUtil.loadImgInFrag(this, evaluateResult.getImage().getWgzp3(), tpdv03.getImageView());
                tpdv03.setImgPath(evaluateResult.getImage().getWgzp3());
                tpdv03.setPhotoBtnState(true);
            }

            if (!TextUtils.isEmpty(evaluateResult.getImage().getWgzp4())) {
                ImageLoadUtil.loadImgInFrag(this, evaluateResult.getImage().getWgzp4(), tpdv04.getImageView());
                tpdv04.setImgPath(evaluateResult.getImage().getWgzp4());
                tpdv04.setPhotoBtnState(true);
            }

            if (!TextUtils.isEmpty(evaluateResult.getImage().getWgzp5())) {
                ImageLoadUtil.loadImgInFrag(this, evaluateResult.getImage().getWgzp5(), tpdv05.getImageView());
                tpdv05.setImgPath(evaluateResult.getImage().getWgzp5());
                tpdv05.setPhotoBtnState(true);
            }

            if (!TextUtils.isEmpty(evaluateResult.getImage().getWgzp6())) {
                ImageLoadUtil.loadImgInFrag(this, evaluateResult.getImage().getWgzp6(), tpdv06.getImageView());
                tpdv06.setImgPath(evaluateResult.getImage().getWgzp6());
                tpdv06.setPhotoBtnState(true);
            }

            if (!TextUtils.isEmpty(evaluateResult.getImage().getWgzp7())) {
                ImageLoadUtil.loadImgInFrag(this, evaluateResult.getImage().getWgzp7(), tpdv07.getImageView());
                tpdv07.setImgPath(evaluateResult.getImage().getWgzp7());
                tpdv07.setPhotoBtnState(true);
            }

            if (!TextUtils.isEmpty(evaluateResult.getImage().getWgzp8())) {
                ImageLoadUtil.loadImgInFrag(this, evaluateResult.getImage().getWgzp8(), tpdv08.getImageView());
                tpdv08.setImgPath(evaluateResult.getImage().getWgzp8());
                tpdv08.setPhotoBtnState(true);
            }
        }
    }

    @Override
    protected void initView() {
        photoViewList = new ArrayList<>(8);
        photoViewList.add(tpdv01);
        photoViewList.add(tpdv02);
        photoViewList.add(tpdv03);
        photoViewList.add(tpdv04);
        photoViewList.add(tpdv05);
        photoViewList.add(tpdv06);
        photoViewList.add(tpdv07);
        photoViewList.add(tpdv08);

        for (int i = 0; i < photoViewList.size(); i++) {
            photoViewList.get(i).setListener(this);
        }

        ivRegisterDate.setOnClickListener(this);
        ivInsuranceDate.setOnClickListener(this);
        ivAnnualInspect.setOnClickListener(this);
        ivChuchang.setOnClickListener(this);

//        PickerList register listener
        llCarbodyColor.setOnClickListener(this);
        llUseType.setOnClickListener(this);
        llCarSeries.setOnClickListener(this);
        llCarBrand.setOnClickListener(this);
        llCarModel.setOnClickListener(this);
        llCarAge.setOnClickListener(this);
        llCarBodyStyle.setOnClickListener(this);
        llBsx.setOnClickListener(this);
        llPfbz.setOnClickListener(this);
        llPfbz.setOnClickListener(this);
        llGasType.setOnClickListener(this);
        llDriveType.setOnClickListener(this);
        llCarGs.setOnClickListener(this);
        llJscColor.setOnClickListener(this);
        llInsuranceCompany.setOnClickListener(this);
        llSeatCount.setOnClickListener(this);
        llPlUnit.setOnClickListener(this);
        llSccj.setOnClickListener(this);

        llCarSourceCity.setOnClickListener(this);
        llChemenCount.setOnClickListener(this);
        ivGotoTop.setOnClickListener(this);
        tvPreviousStep.setOnClickListener(this);
        tvNextStep.setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.iv_register_date:
                DatePickerUtil.show(this.getActivity(), this, true ,  "ivRegisterDate");
                break;
            case R.id.iv_chuchang:
                DatePickerUtil.show(this.getActivity(), this, true , "ivChuchang");
                break;
            case R.id.iv_insurance_date:
                DatePickerUtil.show(this.getActivity(), this, false ,"ivInsuranceDate");
                break;
            case R.id.iv_annual_inspect:
                DatePickerUtil.show(this.getActivity(), this, false ,"ivAnnualInspect");
                break;
            case R.id.iv_goto_top:
                svContent.smoothScrollTo(0, 0);
                break;
            case R.id.ll_pl_unit:
                dataList.clear();
                dataList.add(new PickData("L", "L"));
                dataList.add(new PickData("T", "T"));
                listPicker.setList(String.valueOf(R.id.ll_pl_unit), dataList);
                listPicker.listPickerDialog();
                break;
            case R.id.ll_seat_count:
                loadCarBasicInfo("seats", R.id.ll_seat_count);
                break;
            case R.id.ll_chemen_count:
                loadCarBasicInfo("door", R.id.ll_chemen_count);
                break;
            case R.id.ll_car_source_city:
                Intent intent = new Intent(getActivity(), CarSourceCitySelectActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT_SOURCE_CITY);
                break;
            case R.id.ll_carbody_color:
                loadCarBasicInfo("exteriorcolor", R.id.ll_carbody_color);
                break;
            case R.id.ll_use_type:
                dataList.clear();
                for (int i = 0; i < MyApplication.getInstance().getCarTempAttrList().getAr_isuse().size(); i++) {
                    dataList.add(new CarInfo.CarUseType(String.valueOf(i), MyApplication.getInstance().getCarTempAttrList().getAr_isuse().get(i)));
                }
                listPicker.setList(String.valueOf(R.id.ll_use_type), dataList);
                listPicker.listPickerDialog();
                break;
            case R.id.ll_car_brand:
                Intent intent1 = new Intent(this.getActivity(), SelectCarInfoActivity.class);
                intent1.putExtra(Constants.CAR_BRAND_LEVEL_BRAND, 1);
                startActivityForResult(intent1, REQUEST_CODE_SELECT_CAR_BRAND);
                break;
            case R.id.ll_car_series:
                if (selectedCarBrand == null) {
                    SToast.show("请选择车辆品牌", Gravity.CENTER);
                    return;
                }
                Intent intent2 = new Intent(this.getActivity(), SelectCarInfoActivity.class);
                intent2.putExtra(Constants.CAR_BRAND_LEVEL_BRAND, 2);
                intent2.putExtra("pid", selectedCarBrand.getId());
                startActivityForResult(intent2, REQUEST_CODE_SELECT_CAR_SERIES);
                break;
            case R.id.ll_car_model:
                if (selectedCarSeries == null) {
                    SToast.show("请选择车系", Gravity.CENTER);
                    return;
                }
                Intent intent3 = new Intent(this.getActivity(), SelectCarInfoActivity.class);
                intent3.putExtra(Constants.CAR_BRAND_LEVEL_BRAND, 3);
                intent3.putExtra("pid", selectedCarSeries.getId());
                startActivityForResult(intent3, REQUEST_CODE_SELECT_CAR_MODEL);
                break;
            case R.id.ll_sccj:
                if (selectedCarBrand == null) {
                    SToast.show("请选择车辆品牌");
                    return;
                }
                Log.e(TAG, "onClick: 车辆品牌 ID : " + selectedCarBrand.getId());
                loadCarInfo(PARAMS_LEVEL_CAR_VEHICLE_MANUFACTORY, Integer.parseInt(selectedCarBrand.getId()), new RespCallback<List<CarInfo.CarManufactory>>() {
                            @Override
                            protected void onRequestFailed(String msg) {
                                SToast.show(msg);
                            }

                            @Override
                            protected void onSuccess(List<CarInfo.CarManufactory> data) {
                                listPicker.setList(String.valueOf(R.id.ll_sccj), (ArrayList) data);
                                listPicker.listPickerDialog();
                            }

                            @Override
                            public void onBefore(Request request, int id) {
                                showDialog();
                            }

                            @Override
                            public void onAfter(int id) {
                                dismissDialog();
                            }

                        }
                );
                break;
            case R.id.ll_car_age:
                loadCarBasicInfo("cyear", R.id.ll_car_age);
                break;
            case R.id.ll_car_body_style:
                loadCarBasicInfo("bodystyle", R.id.ll_car_body_style);
                break;
            case R.id.ll_bsx:
                loadCarBasicInfo("trans", R.id.ll_bsx);
                break;
            case R.id.ll_pfbz:
                loadCarBasicInfo("emission", R.id.ll_pfbz);
                break;
            case R.id.ll_drive_type:
                loadCarBasicInfo("drivetrain", R.id.ll_drive_type);
                break;
            case R.id.ll_gas_type:
                loadCarBasicInfo("fueltype", R.id.ll_gas_type);
                break;
            case R.id.ll_car_gs:
                loadCarBasicInfo("cylinders", R.id.ll_car_gs);
                break;
            case R.id.ll_jsc_color:
                loadCarBasicInfo("interiorcolor", R.id.ll_jsc_color);
                break;
            case R.id.ll_insurance_company:
                loadCarBasicInfo("insurer", R.id.ll_insurance_company);
                break;
            case R.id.tv_previous_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToPreviousPage();
                    }
                });
                break;
            case R.id.tv_next_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToNextPage();
                    }
                });
                break;
            default:
                break;

        }
    }

    /**
     * 车辆基础信息列表
     *
     * @param car_item_code
     * @param idTag
     */
    public void loadCarBasicInfo(final String car_item_code, final int idTag) {
        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("field", car_item_code);
        ApiClient.postForm(HttpConstants.GET_CAR_BASIC_INFO, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                SToast.show("数据获取失败");
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response).optJSONObject("data");
                    List<CarBaseInfoData> infoList = new Gson().fromJson(jsonObject.optString(car_item_code), new TypeToken<List<CarBaseInfoData>>() {
                    }.getType());
                    listPicker.setList(String.valueOf(idTag), (ArrayList) infoList);
                    listPicker.listPickerDialog();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }
        });
    }

    /**
     * 获取车辆品牌信息
     * @param level
     * @param pid
     * @param callBack
     */
    public void loadCarInfo(int level, int pid, RespCallback callBack) {
        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        if (level != PARAMS_NOT_NECESSARY)
            params.put("level", String.valueOf(level));
        if (pid != PARAMS_NOT_NECESSARY)
            params.put("pid", String.valueOf(pid));
        ApiClient.postForm(HttpConstants.GET_CAR_BRAND_LIST, params, callBack);
    }


    /**
     * 进入图片选择页面
     */
    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .start(getActivity(), CarBaseInfoFragment.this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PhotoPicker.REQUEST_CODE:
                if (data != null) {
                    String localImgPath = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
                    if (!TextUtils.isEmpty(localImgPath)) {
                        photoViewList.get((int) llRootView.getTag()).setImgPath(localImgPath);
                        photoViewList.get((int) llRootView.getTag()).setPhotoBtnState(true);
                        ImageLoadUtil.loadImgInFrag(this, localImgPath, photoViewList.get((int) llRootView.getTag()).getImageView());
                    }
                }
                break;
            //           删除照片
            case PREVIEW_IMG_REQUEST:
                if (data == null) {
                    return;
                }
                boolean deleteImg = data.getBooleanExtra("DELETE_IMG", false);
                Log.e(TAG, "onActivityResult: " + deleteImg);
                if (deleteImg) {
                    photoViewList.get((int) llRootView.getTag()).setImgPath("");
                    photoViewList.get((int) llRootView.getTag()).setPhotoBtnState(false);
                    photoViewList.get((int) llRootView.getTag()).getImageView().setImageDrawable(null);
                }
                break;
            case REQUEST_CODE_SELECT_SOURCE_CITY:
                if (data != null && resultCode == Activity.RESULT_OK) {
                    CarInfo.CarSourceCity sourceProvince = null, sourceCity = null;
                    if (null != data.getSerializableExtra("SOURCE_CITY")) {
                        sourceCity = (CarInfo.CarSourceCity) data.getSerializableExtra("SOURCE_CITY");
                        tvCarSourceCity.setText(sourceCity.getName());
                        params.put("city", sourceCity.getId());
                    }
                    if (null != data.getSerializableExtra("SOURCE_PROVINCE")) {
                        sourceProvince = (CarInfo.CarSourceCity) data.getSerializableExtra("SOURCE_PROVINCE");
                        params.put("province", sourceProvince.getId());
                        tvCarSourceCity.setText(sourceProvince.getName());
                    }
                    if (sourceProvince != null && sourceCity != null) {
                        tvCarSourceCity.setText(sourceProvince.getName() + sourceCity.getName());
                    }
                }
                break;
            case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    captureManager.galleryAddPic();

                    String path = captureManager.getCurrentPhotoPath();

                    photoViewList.get((int) llRootView.getTag()).setImgPath(path);
                    photoViewList.get((int) llRootView.getTag()).setPhotoBtnState(true);
                    ImageLoadUtil.loadImgInFrag(this, path, photoViewList.get((int) llRootView.getTag()).getImageView());
                }
                break;
            case REQUEST_CODE_SELECT_CAR_BRAND:
                if (null != data && null != data.getSerializableExtra("CAR_BRAND")) {
                    selectedCarBrand = (CarInfo.CarBrand) data.getSerializableExtra("CAR_BRAND");
                    tvCarBrand.setText(selectedCarBrand.getTitle());

                    clearSeries();
                    clearSpec();
                }
                break;
            case REQUEST_CODE_SELECT_CAR_SERIES:
                if (null != data && null != data.getSerializableExtra("CAR_SERIES")) {
                    selectedCarSeries = (CarInfo.CarSeries) data.getSerializableExtra("CAR_SERIES");
                    tvCarSeries.setText(selectedCarSeries.getTitle());

                    clearSpec();
                }
                break;
            case REQUEST_CODE_SELECT_CAR_MODEL:
                if (null != data && null != data.getSerializableExtra("CAR_MODEL")) {
                    selectedCarModel = (CarInfo.CarModel) data.getSerializableExtra("CAR_MODEL");
                    tvCarModel.setText(selectedCarModel.getTitle());
                }
                break;

            default:
                break;
        }
    }


    @Override
    public void onListOK(String tag, InfoData infoData) {

        switch (tag) {
            case R.id.ll_carbody_color + "":
                tvCarbodyColor.setText(infoData.getTitle());
                params.put("exteriorcolor", infoData.getId());
                break;
            case R.id.ll_use_type + "":
                tvUseType.setText(infoData.getTitle());
                params.put("isuse", infoData.getId());
                break;
            case R.id.ll_car_age + "":
                tvCarAge.setText(infoData.getTitle());
                params.put("cyear", infoData.getId());
                break;
            case R.id.ll_car_body_style + "":
                tvCarBodyStyle.setText(infoData.getTitle());
                params.put("bodystyle", infoData.getId());
                break;
            case R.id.ll_bsx + "":
                tvBsx.setText(infoData.getTitle());
                params.put("trans", infoData.getId());
                break;
            case R.id.ll_pfbz + "":
                tvPfbz.setText(infoData.getTitle());
                params.put("emission", infoData.getId());
                break;
            case R.id.ll_car_gs + "":
                tvCarGs.setText(infoData.getTitle());
                params.put("cylinders", infoData.getId());
                break;
            case R.id.ll_jsc_color + "":
                tvJscColor.setText(infoData.getTitle());
                params.put("interiorcolor", infoData.getId());
                break;
            case R.id.ll_insurance_company + "":
                tvInsuranceCompany.setText(infoData.getTitle());
                params.put("insurer", infoData.getId());
                break;
            case R.id.ll_sccj + "":
                if (infoData instanceof CarInfo.CarManufactory) {
                    selectedManufactory = (CarInfo.CarManufactory) infoData;
                    tvSccj.setText(infoData.getTitle());
                    params.put("facturer", infoData.getId());
                }
                break;
            case R.id.ll_gas_type + "":
                tvGasType.setText(infoData.getTitle());
                params.put("fueltype", infoData.getId());
                break;
            case R.id.ll_drive_type + "":
                tvDriveType.setText(infoData.getTitle());
                params.put("drivetrain", infoData.getId());
                break;
            case R.id.ll_pl_unit + "":
                tvPlUnit.setText(infoData.getTitle());
                params.put("dispunit", infoData.getId());
                break;
            case R.id.ll_seat_count + "":
                tvSeatCount.setText(infoData.getTitle());
                params.put("seats", infoData.getId());
                break;
            case R.id.ll_chemen_count + "":
                tvChemenCount.setText(infoData.getTitle());
                params.put("door", infoData.getId());
                break;
            default:
                break;
        }
    }

    @Override
    public void onSaveEvaluateResult(Runnable task) {
        if (null != task)
            this.mTask = task;
        for (int i = 0; i < photoViewList.size(); i++) {
            if (!TextUtils.isEmpty(photoViewList.get(i).getImagePath()) && !photoViewList.get(i).getImagePath().startsWith("http")) {
                uploadImgToOss();
                return;   //只要至少选择过一张图片，就直接return调用uploadImgToOss方法进行上传图片，否则没有选择照片，直接上传其他数据
            }
        }
        saveData();
    }

    private void uploadImgToOss() {
        for (int i = 0; i < photoViewList.size(); i++) {
            if (!TextUtils.isEmpty(photoViewList.get(i).getImagePath()) && !photoViewList.get(i).getImagePath().startsWith("http")) {
                MyApplication.getInstance().getOssService(CarBaseInfoFragment.this).asyncPutImage(OssService.getOssObjectInfo(true),
                        photoViewList.get(i).getImagePath(), String.valueOf(photoViewList.get(i).getItemIndex()));
                ++uploadImgCounter;
                showDialog();
            }
        }
    }

    private void saveData() {
        //        保存修改结果

        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());

//        if (!TextUtils.isEmpty(etDashboardMileage.getText().toString()))
            params.put("mileage", etDashboardMileage.getText().toString());

        if (!TextUtils.isEmpty(tvShangpaiDate.getText().toString()))
            params.put("licdate", String.valueOf(TimeUtils.string2Seconds(tvShangpaiDate.getText().toString())));

        if (!TextUtils.isEmpty(tvChuchangDate.getText().toString()))
            params.put("exwdate", String.valueOf(TimeUtils.string2Seconds(tvChuchangDate.getText().toString())));

        if (!TextUtils.isEmpty(tvChuchangDate.getText().toString()) && !TextUtils.isEmpty(tvShangpaiDate.getText().toString()) && TimeUtils.string2Seconds(tvShangpaiDate.getText().toString()) < TimeUtils.string2Seconds(tvChuchangDate.getText().toString())) {
            SToast.show("\"首次上牌日\"不能早于\"出厂年月\"");
            return;
        }

        if (!TextUtils.isEmpty(etGuohuCount.getText().toString()))
            params.put("transfers", etGuohuCount.getText().toString());

        if (!TextUtils.isEmpty(tvInsuranceDate.getText().toString()))
            params.put("tcidate", String.valueOf(TimeUtils.string2Seconds(tvInsuranceDate.getText().toString())));

        if (!TextUtils.isEmpty(tvAnnualInspectDate.getText().toString()))
            params.put("vaidate", String.valueOf(TimeUtils.string2Seconds(tvAnnualInspectDate.getText().toString())));

//        if (!TextUtils.isEmpty(etPl.getText().toString()))
            params.put("displace", etPl.getText().toString());

        if (!TextUtils.isEmpty(tvPlUnit.getText().toString()))
            params.put("dispunit", tvPlUnit.getText().toString());

//        if (!TextUtils.isEmpty(etPalateNumber.getText().toString()))
            params.put("plate", etPalateNumber.getText().toString());

//        if (!TextUtils.isEmpty(etEngineNumber.getText().toString()))
            params.put("engineno", etEngineNumber.getText().toString());

        if (null != selectedCarBrand)
            params.put("brand", selectedCarBrand.getId());

        if (null != selectedCarSeries)
            params.put("series", selectedCarSeries.getId());

        if (null != selectedCarModel)
            params.put("spec", selectedCarModel.getId());

        if (null != selectedManufactory) {
            params.put("facturer", selectedManufactory.getId());
        }

//        复选框
        params.put("vpt", rgGzsZs.getCheckedRadioButtonId() == R.id.rb_gzszs_checked ? "1" : "0");
        params.put("invoice", rgNewcarVoucher.getCheckedRadioButtonId() == R.id.rb_voucher_checked ? "1" : "0");
        params.put("velic", rgCarLicense.getCheckedRadioButtonId() == R.id.rb_license_checked ? "1" : "0");
        params.put("vrlic", rgCarCertification.getCheckedRadioButtonId() == R.id.rb_certificate_checked ? "1" : "0");
        params.put("tcilic", rgQzBxd.getCheckedRadioButtonId() == R.id.rb_qzbxd_checked ? "1" : "0");
        params.put("sparekey", rgSecondKey.getCheckedRadioButtonId() == R.id.rb_bykey_checked ? "1" : "0");
        params.put("norecord", rgWclWfjl.getCheckedRadioButtonId() == R.id.rb_wclwfjl_checked ? "1" : "0");
        params.put("mortgage", rgSfCfdy.getCheckedRadioButtonId() == R.id.rb_sfcf_checked ? "1" : "0");
        params.put("carryplate", rgDp.getCheckedRadioButtonId() == R.id.rb_dp_checked ? "1" : "0");
        params.put("ccsp", rgCartaxReceipt.getCheckedRadioButtonId() == R.id.rb_cartax_checked ? "1" : "0");
        params.put("vci", rgCommercialInsurance.getCheckedRadioButtonId() == R.id.rb_sybx_checked ? "1" : "0");

        params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());

        if (imgParams == null) {
            imgParams = new HashMap<>();
        }

        imgParams.put("wgzp1", tpdv01.getImagePath());
        imgParams.put("wgzp2", tpdv02.getImagePath());
        imgParams.put("wgzp3", tpdv03.getImagePath());
        imgParams.put("wgzp4", tpdv04.getImagePath());
        imgParams.put("wgzp5", tpdv05.getImagePath());
        imgParams.put("wgzp6", tpdv06.getImagePath());
        imgParams.put("wgzp7", tpdv07.getImagePath());
        imgParams.put("wgzp8", tpdv08.getImagePath());
        params.put("image", new Gson().toJson(imgParams));

        if (MyApplication.getInstance().getEvaluateResult() == null || MyApplication.getInstance().getEvaluateResult().getIroute() == null || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
            int[] iroute = new int[15];
            iroute[CarBaseInfoFragment.PAGE_INDEX] = 1;
            String json = new Gson().toJson(iroute);
            Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
            params.put("iroute", json.substring(1, json.length() - 1));
        } else {
            MyApplication.getInstance().getEvaluateResult().getIroute().set(CarBaseInfoFragment.PAGE_INDEX, 1);
            String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
            params.put("iroute", json.substring(1, json.length() - 1));
            Log.e(TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
        }

        //        根据评估类型进行保存或编辑
        int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();

//       保存新创建、未上传待评估数据
        if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {

            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new RespCallback<EvaluateDetailResult2>() {

                @Override
                protected void onRequestFailed(String msg) {
                    SToast.show(msg);
                    if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                        mTask.run();
                        mTask = null;
                    }
                }

                @Override
                protected void onSuccess(EvaluateDetailResult2 data) {

                    if (null != data) {

                        MyApplication.getInstance().setEvaluateResult(data);

                        if (mTask != null) {
                            mTask.run();
                            mTask = null;
                        }
                    }
                }

                @Override
                public void onBefore(Request request, int id) {
                    showDialog();
                }

                @Override
                public void onAfter(int id) {
                    dismissDialog();
                }
            });

        } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {

            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    // 网络异常
                    if (e instanceof UnknownHostException || e instanceof SocketException) {
                        SToast.show(R.string.tip_network_error, Gravity.CENTER);
                        return;
                    }
                }

                @Override
                public void onResponse(String response, int id) {

                    try {

                        JSONObject obj = new JSONObject(response);
                        if (obj.optInt("code") == 1) {

                            if (mTask != null) {
                                mTask.run();
                                mTask = null;
                            }

                        } else {
                            SToast.show( obj.optString("msg") );
                            if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                                mTask.run();
                                mTask = null;
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onBefore(Request request, int id) {
                    showDialog();
                }

                @Override
                public void onAfter(int id) {
                    dismissDialog();
                }
            });
        }
    }


    private void goToPreviousPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(EvaluateBaseInfoFragment.PAGE_INDEX);
    }

    private void goToNextPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(CarConfigInfoFragment.PAGE_INDEX);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(CarBaseInfoFragment.this);
    }

    @Override
    public void takePhoto(int itemIndex) {
        llRootView.setTag(itemIndex);
        if (!TextUtils.isEmpty(photoViewList.get(itemIndex).getImagePath())) {
            //  有照片，预览照片
            Intent intent = new Intent(getActivity(), PhotoPreViewActivity.class);
            intent.putExtra("IMG_PATH", photoViewList.get(itemIndex).getImagePath());
            this.startActivityForResult(intent, PREVIEW_IMG_REQUEST);
        } else {
            showImgSelectDialog(photoViewList.get(itemIndex).getTextDesc());
        }
    }

    public void showImgSelectDialog(String titleStr) {
        if (null == imgSelectDialog) {
            imgSelectDialog = new ImageSelectDialog(this.getActivity(), this, titleStr);
        } else {
            imgSelectDialog.setTitleStr(titleStr);
        }
        imgSelectDialog.show();
    }

    @Override
    public void onUploadOk(String imgUrl, Object tag) {
        --uploadImgCounter;
        if (!TextUtils.isEmpty(imgUrl)) {
            photoViewList.get(Integer.valueOf((String) tag)).setImgPath(imgUrl);
        }
        if (uploadImgCounter == 0) {
            saveData();
        }
    }

    @Override
    public void onUploadFailed() {
        SToast.show("图片上传失败!");
    }

    private void openSystemCamera() {
        Intent intent = null;
        try {
            intent = captureManager.dispatchTakePictureIntent();
            startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTakePhotoWithSystemCamera() {
        openSystemCamera();
    }


    @Override
    public void onSelectImgOnGallery() {
        pickPhoto();
    }

    @Override
    public void onDatePicked(String year, String month, String day) {
        switch (DatePickerUtil.getTag()) {
            case "ivRegisterDate":
                tvShangpaiDate.setText(new StringBuilder().append(year).append("-").append((month)).append("-").append(day).toString());
                break;
            case "ivInsuranceDate":
                tvInsuranceDate.setText(new StringBuilder().append(year).append("-").append((month)).append("-").append(day).toString());
                break;
            case "ivAnnualInspect":
                tvAnnualInspectDate.setText(new StringBuilder().append(year).append("-").append((month)).append("-").append(day).toString());
                break;
            case "ivChuchang":
                tvChuchangDate.setText(new StringBuilder().append(year).append("-").append((month)).append("-").append(day).toString());
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DatePickerUtil.clearPicker();
    }

    @Override
    public void onOK() {

    }

    public void clearSeries(){
        selectedCarSeries = null;
        tvCarSeries.setText("");
    }

    public void clearSpec(){
        selectedCarModel = null;
        tvCarModel.setText("");
    }

}
